import { h, Ref, ref, shallowRef, watch } from "vue";
import { CURDAction, DynamicFormExpose, FormItemComponentType } from "/@/components/CURDDialog/models";
import type { FormItemData } from "/@/components/CURDDialog/models";
import type { AddUserParams, UserItem } from "/@/api/aiot/user/models";
import { Gender } from "/@/api/aiot/user/models";
import { PatternKey } from "/@/utils/verify";
import { useI18n } from "/@/locales/useI18n";
import { Api, getPositions } from "/@/api/aiot/organization";
import { Api as roleApi } from "/@/api/aiot/role";
import { RequestMethodEnum } from "/@/api/req/httpEnum";
import { useCURD } from "/@/hooks/useCURD";
import { OrganizationItem, OrganizationType } from "/@/api/aiot/organization/models";
import { enumToOptions } from "/@/utils/common";
import { getCountry, getRegionsByParentId } from "/@/api/aiot/zone";
import type { PartialZoneItem, RegionsItem, ZoneItem } from "/@/api/aiot/zone/models";
import type { SelectOptionItem } from "/@/types/antd";
import { CountryData } from "/@/base/data";
import { RoleItem, RoleSearchModel } from "/@/api/aiot/role/models";
import RoleCheckboxList from "./RoleCheckboxList.vue";
import SelectInput from "/@/components/common/SelectInput.vue";
import { findItemByKey, findParents } from "/@/utils/treeData";
import PositionRadioGroup from "./PositionRadioGroup.vue";

export interface UseUserModelOptions {
  getOrgData?: () => Promise<OrganizationItem[]>;
  //平台级用户管理 没有部门
  isPlatform?: boolean;
  getPopupContainer?: (triggerNode?: HTMLElement) => HTMLElement;
  isCreate?: boolean;
  //是否能选角色
  hasRole?: boolean;
}

/**
 * 获取租户级别的用户信息model
 */
export function useUserModel(options?: UseUserModelOptions) {
  const userForm = shallowRef<DynamicFormExpose>();
  const curdDialogForm = shallowRef<DynamicFormExpose>();
  const { t } = useI18n();
  options = options || {};
  let getOrgData: UseUserModelOptions["getOrgData"];
  if (options.getOrgData) {
    getOrgData = options.getOrgData;
  } else {
    const { tableData: orgData, reloadTable: reloadOrgData } = useCURD<OrganizationItem>({
      getDataUrl: Api.getOrgTreeVoByName,
      getDataMethod: RequestMethodEnum.POST,
      loadOnMounted: false,
    });
    getOrgData = async () => {
      if (orgData.value.length > 0) {
        return orgData.value;
      }
      await reloadOrgData();
      return orgData.value;
    };
  }

  const { tableData: roleData, reloadTable: reloadRoleData } = useCURD<RoleItem, RoleSearchModel>({
    getDataUrl: roleApi.getRolesByName,
    getDataMethod: RequestMethodEnum.POST,
    loadOnMounted: false,
  });

  // function regionsToOptions(data: PartialZoneItem[] | null): SelectOptionItem[] {
  //   return data
  //     ? data.map((el) => ({
  //         label: el.regionName,
  //         value: el.regionName,
  //         key: el.regionId,
  //         isLeaf: el.isLeaf,
  //       }))
  //     : [];
  // }

  function getMainInfo(): AddUserParams {
    const data: AddUserParams = {
      nickName: "",
      phone: "",
      companyId: null,
      positionId: "",
      companyEmail: "",
    };
    if (options?.isPlatform) {
      delete data.companyId;
      delete data.positionId;
    }
    if (options?.hasRole) {
      data.roleId = "";
      // data.roleIds = [];
    }
    return data;
  }

  function getMainSetting(): FormItemData[] {
    const data: FormItemData<UserItem>[] = [
      // {
      //   key: "_subTitle",
      //   subTitle: t("common.baseInfo"),
      //   beforeKey: "nickName",
      // },
      {
        key: "companyId",
        label: t("common.department"),
        textKey: "companyShortName",
        type: FormItemComponentType.TREESELECT,
        getData: getOrgData,
        required: true,
        props: {
          fieldNames: { label: "companyShortName", value: "companyId" },
          getPopupContainer: options && options.getPopupContainer,
        },
      },
      {
        key: "positionId",
        label: "岗位",
        labelDes: "目前仅运用于服务工单流程",
        textKey: "positionName",
        requiredMes: "请选择岗位",
        customComponent: h(PositionRadioGroup),
        required: true,
        async getData({ params }) {
          if (params) {
            const data = await getPositions(params);
            return data || [];
          }
          return [];
        },
        props: {
          data: [],
        },
      },
      {
        key: "companyEmail",
        label: t("common.mail"),
        pattern: PatternKey.email,
        max: 32,
      },
      {
        key: "phone",
        label: t("common.cellphone"),
        labelDes: "默认密码为888888",
        pattern: PatternKey.cellphone,
        required: true,
        extraComponent: ({ curAction }) => {
          if (curAction === CURDAction.UPDATE) {
            return h(
              "div",
              {
                class: "text-color-secondary mt-2",
              },
              t("aiot.user.phoneEditTip")
            );
          } else {
            return null;
          }
        },
      },
      {
        key: "nickName",
        label: t("common.personName"),
        pattern: PatternKey.name,
        max: 32,
        required: true,
      },
    ];
    if (options?.isPlatform) {
      let index = data.findIndex((el) => el.key === "companyId");
      data.splice(index, 1);
      index = data.findIndex((el) => el.key === "positionId");
      data.splice(index, 1);
    }
    if (options?.hasRole) {
      data.push({
        key: "roleId",
        label: t("aiot.role.info"),
        required: true,
        requiredMes: "请选择角色",
        customComponent: h(RoleCheckboxList),
        interValueToFormValue(value, model, el) {
          el.text = (model.roles as string) || "--";
          return value;
        },
        async getData() {
          if (roleData.value.length > 0) {
            return roleData.value;
          }
          await reloadRoleData({ roleName: "" });
          return roleData.value;
        },
        props: {
          data: [],
        },
      });
    }
    return data;
  }

  function getSubInfo(): AddUserParams {
    return {
      // region: "",
      // location: "",
      gender: Gender.secrecy,
      description: "",
    };
  }

  function getSubSetting(): FormItemData[] {
    return [
      {
        key: "gender",
        label: t("common.sex"),
        type: FormItemComponentType.SELECT,
        textKey: "label",
        valueKey: "value",
        props: {
          options: enumToOptions(Gender, "gender"),
        },
      },
      // {
      //   label: t("aiot.tenant.region"),
      //   key: "location",
      //   max: 256,
      //   // type: FormItemComponentType.TEXTAREA,
      //   customComponent: h(SelectInput, {
      //     onClick() {
      //       locDgVisible.value = true;
      //     },
      //   }),
      // },
      // {
      //   label: t("aiot.tenant.region"),
      //   key: "region",
      //   type: FormItemComponentType.CASCADER,
      //   formValueToInterValue(value) {
      //     return value ? value.join("-") : "";
      //   },
      //   interValueToFormValue(value, model, el) {
      //     el.text = value ? value : "--";
      //     return value ? value.split("-") : [];
      //   },
      //   async getData() {
      //     let countryData = await getCountry();
      //     if (countryData) {
      //       let china = countryData.find((el) => el.regionName === CountryData.china);
      //       if (china) {
      //         const result = await getRegionsByParentId({ parentId: china.regionId as string });
      //         return regionsToOptions(result || []);
      //       }
      //     }
      //     return [];
      //   },
      //   props: {
      //     placeholder: t("aiot.tenant.plzChooseRegion"),
      //     options: [],
      //     placement: options && options.isCreate ? "bottomLeft" : "bottomRight",
      //     getPopupContainer: options && options.getPopupContainer,
      //     async loadData(selectedOptions) {
      //       const targetOption = selectedOptions[selectedOptions.length - 1];
      //       targetOption.loading = true;
      //       const data = await getRegionsByParentId({ parentId: targetOption.key });
      //       if (data) {
      //         targetOption.children = regionsToOptions(data);
      //       }
      //       targetOption.loading = false;
      //     },
      //     dropdownClassName: "sl-cascader-menus",
      //   },
      // },
      // {
      //   label: t("common.address"),
      //   key: "location",
      //   type: FormItemComponentType.TEXTAREA,
      //   max: 64,
      // },
      {
        label: t("common.simpleDes"),
        key: "description",
        type: FormItemComponentType.TEXTAREA,
        max: 256,
      },
    ];
  }
  const userModel = ref<AddUserParams>(
    options.isPlatform ? { ...getMainInfo() } : { ...getMainInfo(), ...getSubInfo() }
  );
  if (!options.isPlatform) {
    watch(
      () => userModel.value.companyId,
      async (companyId) => {
        if (getOrgData) {
          //找到最近的公司父节点
          const orgData = await getOrgData();
          const re = findItemByKey(orgData, companyId as string, "companyId");
          if (re && re.item) {
            const formIns = userForm.value || curdDialogForm.value;
            if (re.item.organizationType === OrganizationType.company && formIns) {
              //所选的就是公司 根据公司加载职位数据
              formIns.reloadFormItemComponentData("positionId", re.item.companyId);
              return;
            }
          } else {
            return;
          }
          //所选的不是公司 遍历全部父节点 找到最近的公司节点
          const pIds: string[] = [];
          const pData: OrganizationItem[] = [];
          findParents(orgData, companyId as string, "companyId", pIds, pData);
          let targetCompany: OrganizationItem | null = null;
          if (pData.length > 0) {
            if (pData[pData.length - 1].organizationType === OrganizationType.company) {
              targetCompany = pData[pData.length - 1];
            } else {
              for (let i = 0; i < pData.length; i++) {
                if (pData[i].organizationType !== OrganizationType.company) {
                  targetCompany = pData[i - 1];
                  break;
                }
              }
            }
            const formIns = userForm.value || curdDialogForm.value;
            if (targetCompany && formIns) {
              // console.log("找到最近的公司父节点", targetCompany);
              //根据公司加载职位数据
              formIns.reloadFormItemComponentData("positionId", targetCompany.companyId);
            }
          }
        }
      }
    );
  }
  const subModel = ref<AddUserParams>({ ...getSubInfo() });

  const locDgVisible = ref(false);
  function chooseLoc(e: RegionsItem) {
    userModel.value.region = e.adcode;
    userModel.value.location = e.formattedAddress;
    subModel.value.region = e.adcode;
    subModel.value.location = e.formattedAddress;
  }
  return {
    userModel,
    userModelFormSetting: ref<FormItemData[]>(
      options.isPlatform ? [...getMainSetting()] : [...getMainSetting(), ...getSubSetting()]
    ),
    subModel,
    subModelFormSetting: ref<FormItemData[]>([...getSubSetting()]),
    mainModel: ref<AddUserParams>({ ...getMainInfo() }),
    mainModelFormSetting: ref<FormItemData[]>([...getMainSetting()]),
    getOrgData,
    chooseLoc,
    locDgVisible,
    userForm,
    curdDialogForm,
  };
}
